/**
 * @description: base64 to blob
 */
export function dataURLtoBlob(base64Buf: string): Blob {
  const parts = base64Buf.split(',');

  if (parts.length !== 2) {
    throw new Error('Invalid data URL format: Expected exactly one comma.');
  }

  const [metadata, base64Data] = parts;

  const mimeMatch = (metadata as string).match(/:(.*?);/);
  if (!mimeMatch) {
    throw new Error('Invalid data URL format');
  }
  const mime = mimeMatch[1];

  const binaryString = window.atob(base64Data as string);

  const byteArray = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    byteArray[i] = binaryString.codePointAt(i) as number;
  }

  // Create a Blob from the Uint8Array and the MIME type
  return new Blob([byteArray], { type: mime });
}

/**
 * img url to base64
 * @param url
 */
export function urlToBase64(url: string, mineType?: string): Promise<string> {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement(
      'CANVAS',
    ) as Nullable<HTMLCanvasElement>;
    // const ctx = canvas!.getContext('2d');

    const ctx = canvas.getContext('2d');
    if (!ctx) {
      return reject(
        new Error('Unable to get 2D rendering context for the canvas.'),
      );
    }

    const img = new Image();
    img.crossOrigin = '';

    const loadHandler: () => void = () => {
      try {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        const dataURL = canvas.toDataURL(mineType || 'image/png');
        URL.revokeObjectURL(img.src); // Clean up if the image was loaded from an object URL
        resolve(dataURL);
      } catch (error) {
        reject(error);
      } finally {
        canvas = null; // Nullify to help garbage collection, TypeScript knows it's always null here
      }
    };

    const errorHandler: (event: Event) => void = (event) => {
      reject(
        new Error(
          `Failed to load image: ${(event.target as HTMLImageElement)?.src || url}`,
        ),
      );
    };

    img.addEventListener('load', loadHandler);
    img.addEventListener('error', errorHandler);
    img.src = url;
  });
}

export const errImg =
  '';
